package com.zxw.auth.exception;

import com.zxw.common.api.ApiResult;
import com.zxw.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * OAuth2Exception异常
 */
@Slf4j
public class WebResponseTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception exception) {
        log.error("认证服务器异常", exception);
        ApiResult<String> result = resolveException(exception);
        return ResponseEntity.status(HttpStatus.OK).body(new CustomOauthException(result.getMessage()));
    }

    private ApiResult<String> resolveException(Exception e) {
        if (e instanceof UnsupportedGrantTypeException) {
            //不支持的认证方式
            return ApiResult.failed(ResultCode.UNSUPPORTED_GRANT_TYPE);
        } else if (e instanceof InvalidGrantException) {
            //用户名或密码异常
            return ApiResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户名或密码异常
            System.out.println(e.getMessage());
            if ("账户被禁用".equals(e.getMessage())) {
                return ApiResult.failed(ResultCode.DISABLED_EXCEPTION);
            }
            if ("用户名不存在".equals(e.getMessage())) {
                return ApiResult.failed(ResultCode.LOGIN_USER_NAME_NOT_FOUND);
            }
            return ApiResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);

        }
        // 默认500
        return ApiResult.failed(ResultCode.FAILED);
    }
}
